package com.dashan.servlets;

import static com.dashan.Constants.USERNAME;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;

import com.dashan.backend.datastore.DsFriendInvitation;
import com.dashan.backend.datastore.FriendInvitationDao;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetPendingFriendInvitationServlet extends DashanPrivateServlet {
    
    @Override
    public String getUrlPattern() {
        return "/getpendingfriendinvitation";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        
        FriendInvitationDao dao = new FriendInvitationDao();
        try {
            List<DsFriendInvitation> invitations = 
                dao.getFriendInvitationTo(params.get(USERNAME).stringValue());
            Document xmlDoc = XmlHelper.createXmlDocument("response");
            for (DsFriendInvitation invitation : invitations) {
                xmlDoc.getDocumentElement().appendChild(invitation.getXmlElement(xmlDoc));
            }
            resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException(e.getMessage());
        } finally {
            dao.commit();
        }
    }
}
